using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using MySql.Data.MySqlClient;

namespace Calendar
{
    public partial class frmCalendarView: Form
    {
        DataTable dt = new DataTable();
        int CurrMonth = 0, CurrYear = 0;

        public frmCalendarView()
        {
            InitializeComponent();
        }

        private void frmCalendarView_Load(object sender, EventArgs e)
        {
            // 393,154 width height (size)
            DayOfWeek dow = DateTime.Now.DayOfWeek;
            Console.WriteLine( dow.ToString()); //Monday
            //Day.Monday 
            Console.WriteLine(DateTime.DaysInMonth(2010, 4));
            DateTime.IsLeapYear (2010); // true / false
            //DateTime.Today;  // current date
            DateTime.Today.AddDays(1);
            Console.WriteLine(DateTime.Today.Month.ToString());
            //DateTime.Parse("04/01/2010",


            //btnTest_Click(sender, e);
            UpdateCalender();
            //UpdateCalender();

            //UpdateCalender();
            //btnNextMonth_Click(sender, e);
            //btnPrevMonth_Click(sender, e);

            //Icon_02.ico
            //notifyIcon1.Icon = new System.Drawing.Icon(System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal)  + @"\Icon.ico");
            //notifyIcon1.Icon =   new System.Drawing.Icon(Application.StartupPath+"\\Icon_02.ico");
            //notifyIcon1.Visible = true;
            //notifyIcon1.Text = "SMART Manager Calendar";

            ////this.Visible = false;
            ////this.ShowInTaskbar = false;
            ////this.WindowState = FormWindowState.Minimized;

            //ContextMenu mnuContextMenu = new ContextMenu();
            //this.ContextMenu = mnuContextMenu;

            //MySqlConnection con = new MySqlConnection("server=localhost;database=smartPM;uid=root;"); //burhan_smartmanager   password=abcdaaa
            //con.Open();           
            //MySqlCommand cmd = new MySqlCommand("select description,startdate,estimatedEndDate from task");
            //cmd.Connection =con;
            //MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            //DataTable dt=new DataTable();
            //da.Fill(dt);
            //con.Close();
        }

        void init()
        {
            dt = new DataTable();
            dt.Columns.Add(new DataColumn("SU"));
            dt.Columns.Add(new DataColumn("MO"));
            dt.Columns.Add(new DataColumn("TU"));
            dt.Columns.Add(new DataColumn("WD"));
            dt.Columns.Add(new DataColumn("TH"));
            dt.Columns.Add(new DataColumn("FR"));
            dt.Columns.Add(new DataColumn("SA"));
            DataRow r = dt.NewRow();
            dt.Rows.Add(r);
            DataRow r2 = dt.NewRow();
            dt.Rows.Add(r2);
            DataRow r3 = dt.NewRow();
            dt.Rows.Add(r3);
            DataRow r4 = dt.NewRow();
            dt.Rows.Add(r4);
            DataRow r5 = dt.NewRow();
            dt.Rows.Add(r5);
            DataRow r6 = dt.NewRow();
            dt.Rows.Add(r6);


            dgvCalendar.DataSource = dt;
            for (int i = 0; i < 7; i++)
            {
                dgvCalendar.Columns[i].Width = 50;
                dgvCalendar.Columns[i].ReadOnly  = true;
            }
            
        }

        string getDayShortName( DayOfWeek dow)
        {
            string dayShortName = "";
            if (dow.Equals(DayOfWeek.Sunday))
                dayShortName = "SU";
            else if (dow.Equals(DayOfWeek.Monday))
                dayShortName = "MO";
            else if (dow.Equals(DayOfWeek.Tuesday))
                dayShortName = "TU";
            else if (dow.Equals(DayOfWeek.Wednesday))
                dayShortName = "WD";
            else if (dow.Equals(DayOfWeek.Thursday))
                dayShortName = "TH";
            else if (dow.Equals(DayOfWeek.Friday))
                dayShortName = "FR";
            else if (dow.Equals(DayOfWeek.Saturday))
                dayShortName = "SA";
            return dayShortName;
        }

        string getMonthName(int monthId)
        {
            if (monthId == 1) return "January";
            else if (monthId == 2) return "February";
            else if (monthId == 3) return "March";
            else if (monthId == 4) return "April";
            else if (monthId == 5) return "May";
            else if (monthId == 6) return "June";
            else if (monthId == 7) return "July";
            else if (monthId == 8) return "August";
            else if (monthId == 9) return "September";
            else if (monthId == 10) return "October";
            else if (monthId == 11) return "November";
            else if (monthId == 12) return "December";
            else return "";
        }

        void UpdateCalender() // Uses global vars CurrMonth and CurrYear
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            init();
            ///////////
            DateTime d;
            DateTime d2;

            DayOfWeek dow = DayOfWeek.Friday;
            int firstDayCol = 0;
            if (CurrMonth == 0) CurrMonth = DateTime.Today.Month;
            if (CurrYear == 0) CurrYear = DateTime.Today.Year ;

            cboMonth.Text = getMonthName(CurrMonth);
            //d = DateTime.Parse(DateTime.Today.Month.ToString() + "/1/" + DateTime.Today.Year.ToString());
            d = DateTime.Parse(CurrMonth.ToString() + "/1/" + CurrYear.ToString());
            d2 = DateTime.Parse(CurrMonth.ToString() + "/" + DateTime.DaysInMonth(CurrYear, CurrMonth) + "/" + CurrYear.ToString());
            
            dow = d.DayOfWeek;

            if (dow.Equals(DayOfWeek.Sunday))
                firstDayCol = 0;
            else if (dow.Equals(DayOfWeek.Monday))
                firstDayCol = 1;
            else if (dow.Equals(DayOfWeek.Tuesday))
                firstDayCol = 2;
            else if (dow.Equals(DayOfWeek.Wednesday))
                firstDayCol = 3;
            else if (dow.Equals(DayOfWeek.Thursday))
                firstDayCol = 4;
            else if (dow.Equals(DayOfWeek.Friday))
                firstDayCol = 5;
            else if (dow.Equals(DayOfWeek.Saturday))
                firstDayCol = 6;
            ///////////

            MySqlConnection con = new MySqlConnection("server=localhost;database=smartPM;uid=root;"); //burhan_smartmanager   password=abcdaaa
            con.Open();
            string qry = "";
            //if (GlobalInfo.UserRole == GlobalInfo.userRole.ProjectManager)
            if (GlobalInfo.UserRole == 2) // ProjectManager
            {
                qry = "select description,startdate,estimatedEndDate from task where (( startdate between '" + d.ToString("yyyy-MM-dd") + "' and '" + d2.ToString("yyyy-MM-dd") + "' ) or  ( estimatedEndDate between '" + d.ToString("yyyy-MM-dd") + "' and '" + d2.ToString("yyyy-MM-dd") + "' )) ";
                qry += " and projectid = (select projectid from project where createdby=(select loginId from user where user.loginname='" + GlobalInfo.UserId + "')) ";
            }
            else
            {
                qry = "select description,startdate,estimatedEndDate from task where (( startdate between '" + d.ToString("yyyy-MM-dd") + "' and '" + d2.ToString("yyyy-MM-dd") + "' ) or  ( estimatedEndDate between '" + d.ToString("yyyy-MM-dd") + "' and '" + d2.ToString("yyyy-MM-dd") + "' )) and resourceid= (SELECT resource.resourceid FROM resource INNER JOIN user ON (resource.userid = user.loginid) and user.loginname='" + GlobalInfo.UserId + "') ";
            }
            MySqlCommand cmd = new MySqlCommand(qry);
            cmd.Connection = con;
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataTable dtTasks = new DataTable();
            da.Fill(dtTasks);
            con.Close();

            DataGridViewCellStyle styleRedDue = new DataGridViewCellStyle();
            styleRedDue.BackColor = Color.Red;
            DataGridViewCellStyle styleGreenStart = new DataGridViewCellStyle();
            styleGreenStart.BackColor = Color.Green;
            DataGridViewCellStyle styleOrangeStartNend = new DataGridViewCellStyle();
            styleOrangeStartNend.BackColor = Color.Orange;

            int rowIdx = 0;
            for (int day = 1; day < DateTime.DaysInMonth(CurrYear, CurrMonth) + 1; day++)
            {
                d = DateTime.Parse(CurrMonth.ToString() + "/" + day.ToString() + "/" + CurrYear.ToString());
                dow = d.DayOfWeek;
                //Console.WriteLine(day + ":: " + dow.ToString());

                if (((firstDayCol + day) % 7) == 0)
                    rowIdx = (firstDayCol + day) / 7 - 1;
                else
                    rowIdx = (firstDayCol + day) / 7;

                string dayShortName = getDayShortName(dow);
                dt.Rows[rowIdx][dayShortName] = day.ToString();

                bool startOfTask = false, endOfTask = false;
                string startTaskName = "", endTaskName = "";
                for (int t = 0; t < dtTasks.Rows.Count ; t++)
                {
                    DateTime startDt =DateTime.Parse( dtTasks.Rows[t]["startdate"].ToString());
                    DateTime endDt = DateTime.Parse(dtTasks.Rows[t]["estimatedEndDate"].ToString());
                    if (startDt.Equals(d)) { startOfTask = true; startTaskName = dtTasks.Rows[t]["description"].ToString(); }
                    if (endDt.Equals(d)) { endOfTask = true; endTaskName = dtTasks.Rows[t]["description"].ToString(); }
                }

                if ((startOfTask == true) && (endOfTask == false ))
                {
                    dgvCalendar.Rows[rowIdx].Cells[dayShortName].ToolTipText = "Start date of '" + startTaskName + "'";
                    dgvCalendar.Rows[rowIdx].Cells[dayShortName].Style = styleGreenStart;
                }
                if ((startOfTask == false) && (endOfTask == true))
                {
                    dgvCalendar.Rows[rowIdx].Cells[dayShortName].ToolTipText = "End date of '" + endTaskName + "'";
                    dgvCalendar.Rows[rowIdx].Cells[dayShortName].Style = styleRedDue;
                }
                if ((startOfTask == true) && (endOfTask == true))
                {
                    dgvCalendar.Rows[rowIdx].Cells[dayShortName].ToolTipText = "Start date of '" + startTaskName + "', End date of '" + endTaskName + "'";
                    dgvCalendar.Rows[rowIdx].Cells[dayShortName].Style = styleOrangeStartNend;
                }
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("SU"));
            dt.Columns.Add(new DataColumn("MO"));
            dt.Columns.Add(new DataColumn("TU"));
            dt.Columns.Add(new DataColumn("WD"));
            dt.Columns.Add(new DataColumn("TH"));
            dt.Columns.Add(new DataColumn("FR"));
            dt.Columns.Add(new DataColumn("SA"));
            DataRow r = dt.NewRow();
            dt.Rows.Add(r);
            DataRow r2 = dt.NewRow();
            dt.Rows.Add(r2);
            DataRow r3 = dt.NewRow();
            dt.Rows.Add(r3);
            DataRow r4 = dt.NewRow();
            dt.Rows.Add(r4);
            DataRow r5 = dt.NewRow();
            dt.Rows.Add(r5);
            DataRow r6 = dt.NewRow();
            dt.Rows.Add(r6);


            dgvCalendar.DataSource = dt;
            for (int i=0; i < 7; i++)
            dgvCalendar.Columns[i].Width = 60;

            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.BackColor=Color.Red;
            dgvCalendar.Rows[1].Cells["SU"].ToolTipText = "End date of 'Manage Project'";
            dgvCalendar.Rows[1].Cells["SU"].Style = style;

            ///////////
            DateTime d;
            DayOfWeek dow=DayOfWeek.Friday   ;
            int firstDayCol = 0;
            d = DateTime.Parse(DateTime.Today.Month.ToString() + "/1/" + DateTime.Today.Year.ToString());
            dow = d.DayOfWeek;

            if (dow.Equals(DayOfWeek.Sunday))
                firstDayCol = 0;
            else if (dow.Equals(DayOfWeek.Monday))
                firstDayCol = 1;
            else if (dow.Equals(DayOfWeek.Tuesday))
                firstDayCol = 2;
            else if (dow.Equals(DayOfWeek.Wednesday))
                firstDayCol = 3;
            else if (dow.Equals(DayOfWeek.Thursday))
                firstDayCol = 4;
            else if (dow.Equals(DayOfWeek.Friday))
                firstDayCol = 5;
            else if (dow.Equals(DayOfWeek.Saturday ))
                firstDayCol = 6;
            ///////////

            int rowIdx = 0;
            for (int day = 1; day < DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month) + 1; day++)
            {
                d = DateTime.Parse(DateTime.Today.Month.ToString() + "/" + day.ToString() + "/" + DateTime.Today.Year.ToString());
                dow = d.DayOfWeek;
                Console.WriteLine(day + ":: " + dow.ToString());

                if (((firstDayCol + day) % 7) ==0)
                    rowIdx = (firstDayCol + day) / 7 -1;
                else 
                rowIdx = (firstDayCol + day) / 7;

                if (dow.Equals( DayOfWeek.Sunday))
                    dt.Rows[rowIdx]["SU"] = day.ToString();
                else if (dow.Equals(  DayOfWeek.Monday))
                    dt.Rows[rowIdx]["MO"] = day.ToString();
                else if (dow.Equals( DayOfWeek.Tuesday))
                    dt.Rows[rowIdx]["TU"] = day.ToString();
                else if (dow.Equals(  DayOfWeek.Wednesday))
                    dt.Rows[rowIdx]["WD"] = day.ToString();
                else if (dow.Equals( DayOfWeek.Thursday))
                    dt.Rows[rowIdx]["TH"] = day.ToString();
                else if (dow.Equals(  DayOfWeek.Friday))
                    dt.Rows[rowIdx]["FR"] = day.ToString();
                else if (dow.Equals(  DayOfWeek.Saturday ))
                    dt.Rows[rowIdx]["SA"] = day.ToString();
            }

        }

        private void btnPrevYear_Click(object sender, EventArgs e)
        {
            CurrYear = CurrYear - 1;
            txtYear.Text = CurrYear.ToString();
            UpdateCalender();
        }

        private void btnNextYear_Click(object sender, EventArgs e)
        {
            CurrYear = CurrYear + 1;
            txtYear.Text = CurrYear.ToString();
            UpdateCalender();
        }

        private void btnNextMonth_Click(object sender, EventArgs e)
        {
            if (CurrMonth <12) CurrMonth = CurrMonth + 1;
            else if (CurrMonth == 12)
            {
                CurrMonth = 1;
                CurrYear = CurrYear + 1;
                txtYear.Text = CurrYear.ToString();
            }

            cboMonth.SelectedIndex = CurrMonth - 1;
            UpdateCalender();
        }

        private void btnPrevMonth_Click(object sender, EventArgs e)
        {
            if (CurrMonth > 1) CurrMonth = CurrMonth - 1;
            else if (CurrMonth == 1)
            {
                CurrMonth = 12;
                CurrYear = CurrYear - 1;
                txtYear.Text = CurrYear.ToString();
            }
            cboMonth.SelectedIndex = CurrMonth - 1;
            UpdateCalender();
        }

        private void calendarToolStripMenuItem_Click(object sender, EventArgs e)
        {
             
            //this.Visible = true;
            //this.ShowInTaskbar = false;
            //this.WindowState = FormWindowState.Normal  ;
            //this.Show();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            this.ShowInTaskbar = false;
            this.WindowState = FormWindowState.Minimized;
        }

        private void txtYear_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Convert.ToInt32(e.KeyChar) = 0;
            //e.KeyChar = '0' ;
            e.Handled = true;
        }

        private void dgvCalendar_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //int r=dgvCalendar.CurrentCell.RowIndex;
            //int c=dgvCalendar.CurrentCell.ColumnIndex ;
            //MessageBox.Show(dgvCalendar.Rows[r].Cells[c].Value.ToString());
        }

        private void dgvCalendar_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //int r = dgvCalendar.CurrentCell.RowIndex;
            //int c = dgvCalendar.CurrentCell.ColumnIndex;
            //MessageBox.Show(dgvCalendar.Rows[r].Cells[c].Value.ToString());
        }

        private void dgvCalendar_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int r = dgvCalendar.CurrentCell.RowIndex;
            int c = dgvCalendar.CurrentCell.ColumnIndex;
            string day = dgvCalendar.Rows[r].Cells[c].Value.ToString();
            //MessageBox.Show(dgvCalendar.Rows[r].Cells[c].Value.ToString());
            DateTime dt = DateTime.Parse(CurrMonth.ToString() + "/" + day + "/" + CurrYear.ToString());
            frmTaskDetail task = new frmTaskDetail(dt );
            task.Show();
        }

        private void signInToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //frmLogin frm = new frmLogin();
            //frm.Show();
        }
    }
}